from sanic.views import HTTPMethodView
from sanic.response import text, json
import time

from processing.comm import sqlOrder, sqlPaging,set_status
from processing.other_func import ProToken, Sercret_all, Serialization, Random_id, date_format
import json as jn
import re
from processing.Sql_DataFrom import ProJosn
import requests


# 商品规格模版列表
class goodsServiceGuaranteeList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        try:
            sql = f"""
                        select id,title,sort,details,icon,status,ctime from serviceGuarantee where merchant_id='{user_id}'
                    """
            tol = f""" SELECT COUNT(*) FROM serviceGuarantee where merchant_id='{user_id}' """

            if keyword:
                sql += f" and  title LIKE '%{keyword}%' "
                tol += f" and  title LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                             'total': tol_data[0]
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsServiceGuaranteeList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


#商品服务保障添加
class goodsServiceGuaranteeAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "insert into serviceGuarantee(title,sort,details,icon,status,merchant_id,ctime) VALUES(%s,%s,%s,%s,%s,%s,now())"
            db.insert(sql, (
                html_data['title'],
                int(html_data['sort']),
                html_data['details'],
                html_data['icon'],
                set_status(html_data['status']),
                user_id,
            ))
            return json({'code': 200,
                         'message': "添加成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsServiceGuaranteeAdd', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 商品服务保障删除
class goodsServiceGuaranteeDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from serviceGuarantee where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsServiceGuaranteeDel', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

#商品服务保障添加
class goodsServiceGuaranteeEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:

            sql = """
                update serviceGuarantee set title=%s,sort=%s,details=%s,icon=%s,status=%s,ctime=now() where merchant_id=%s and id=%s
            """
            db.update(sql, (
                html_data['title'],
                html_data['sort'],
                html_data['details'],
                html_data['icon'],
                set_status(html_data['status']),
                user_id,
                html_data['id']
            ))
            return json({'code': 200,
                         'message': "编辑成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsServiceGuaranteeEdit', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)